﻿namespace instamuz.Application.Services.Impl
{
    using System;
    using System.Security.Principal;
    using System.Web;
    using System.Web.Security;
    using Domain.Entities;

    public class AuthenticationService : IAuthenticationService
    {
        public void SignIn(Account account, bool createPersistentCookie)
        {
            var accountEntry = new AccountEntry(account);

            var authTicket = new FormsAuthenticationTicket(1,
                                                           account.Login,
                                                           DateTime.Now,
                                                           DateTime.Now.AddDays(21),
                                                           createPersistentCookie,
                                                           accountEntry.Serialize());

            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                Expires = DateTime.Now.Add(FormsAuthentication.Timeout),
            };

            HttpContext.Current.Response.Cookies.Add(authCookie);

            var identity = new CustomIdentity(accountEntry, authTicket.Name);
            HttpContext.Current.User = new GenericPrincipal(identity, new string[] {});
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}